package frame.util.shiro;

import frame.system.to.User;
import frame.util.FrameUtil;
import org.springframework.util.StringUtils;

/**
 * 系统用户密码规则<br>
 *
 */
public class UserMD5 {

    public static final String DEFAULT_PROJECT_NAME = "frame2";
    public static final String DEFAULT_PASSWORD = "123456";
    public static final int DEFAULT_SALT_LENGTH = 6;

    public static void main(String[] args) {
        User user = new User();
        user.setUsername("15298025226");
        user.setPassword(DEFAULT_PASSWORD);
        createMd5Salt(user);
        System.out.println(String.format("UPDATE sys_user SET password='%s',salt='%s' WHERE username='%s'",
                user.getPassword(),user.getSalt(),user.getUsername()));
    }

    /**
     * 生成md5密码和盐
     * @param user
     */
    public static void createMd5Salt(User user) {
        if (user == null) throw new IllegalArgumentException("要设置密码加密的用户为【NULL】");
        String pwd = user.getPassword();
        if (StringUtils.isEmpty(pwd))  pwd = DEFAULT_PASSWORD;
        String salt = FrameUtil.randString(DEFAULT_SALT_LENGTH);
        // 开始加密
        String md5 = doMd5(pwd, salt);
        user.setPassword(md5);
        user.setSalt(salt);
    }

    /**
     * 账号md5加密
     * @param pwd 明文密码
     * @param salt 盐
     * @return
     */
    public static String doMd5(String pwd,String salt) {
        // password + project_name
        String md5 = FrameUtil.md5(pwd + DEFAULT_PROJECT_NAME);
        // md5 + salt
        md5 = FrameUtil.md5(md5 + salt);
        return md5;

    }

}
